import { Provide, Inject } from '@midwayjs/core';
import { PrismaService } from './prisma.service';
import { User } from '@prisma/client';

@Provide()
export class OrderService {
  @Inject()
  prisma: PrismaService;

  /**
   * 创建一个新订单
   * @param user 创建订单的用户
   * @param planCode 会员计划代码 (e.g., 'monthly', 'yearly')
   */
  async createOrder(user: User, planCode: string) {
    // 1. 根据 planCode 查找会员计划
    const plan = await this.prisma.membershipPlan.findUnique({
      where: { code: planCode },
    });

    if (!plan) {
      throw new Error('指定的会员计划不存在');
    }

    // 2. 生成唯一的订单号 (简单实现)
    const orderNo = `ORDER_${Date.now()}_${user.id}`;

    // 3. 创建订单
    const order = await this.prisma.order.create({
      data: {
        orderNo,
        amount: plan.price,
        status: 0, // 0: 待支付
        payChannel: 'wechat', // 默认为微信支付
        userId: user.id,
        planId: plan.id,
        planSnapshot: plan, // 将计划详情存为快照
      },
    });

    return order;
  }
}
